﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tunynet;
using Tunynet.Caching;
using Tunynet.Repositories;


namespace Spacebuilder.Common
{
    public class BaseCaseRepository : Repository<BaseCase>, IBaseCaseRepository
    {

        /// <summary>
        /// 通过用户ID查找
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public BaseCase BaseCaseOfUser(long userId)
        {
            StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "userId", userId));
            cacheKey.AppendFormat("BaseCaseOfUser");
            IEnumerable<BaseCase> BaseCaseIds = cacheService.Get<IEnumerable<BaseCase>>(cacheKey.ToString());
            if (BaseCaseIds == null || BaseCaseIds.Count() == 0)
            {
                var sql = PetaPoco.Sql.Builder;
                sql.Select("*")
                .From("spb_BaseCases")
                .Where("UserId = @0", userId);
                BaseCaseIds = CreateDAO().Fetch<BaseCase>(sql);
                cacheService.Set(cacheKey.ToString(), BaseCaseIds, CachingExpirationType.UsualObjectCollection);
            }
            return BaseCaseIds.FirstOrDefault();
        }

        /// <summary>
        /// 获取所有用户个人基本信息
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        public IEnumerable<long> GetBaseCaseOfUser(long userId)
        {
            StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "userId", userId));
            cacheKey.AppendFormat("GetBaseCaseOfUser");
            IEnumerable<long> BaseCaseIds = cacheService.Get<IEnumerable<long>>(cacheKey.ToString());
            if (BaseCaseIds == null || BaseCaseIds.Count() == 0)
            {
                var sql = PetaPoco.Sql.Builder;
                sql.Select("id")
                .From("spb_BaseCases")
                .Where("UserId = @0", userId);
                BaseCaseIds = CreateDAO().FetchFirstColumn(sql).Cast<long>();
                cacheService.Set(cacheKey.ToString(), BaseCaseIds, CachingExpirationType.UsualObjectCollection);
            }
            return BaseCaseIds;
        }

        /// <summary>
        /// 根据用户ID列表获取工作经历ID列表，本方法现用于用户搜索功能的索引生成
        /// </summary>
        /// <param name="userIds">用户ID列表</param>
        /// <returns>工作经历ID列表</returns>
        public IEnumerable<long> GetEntityIdsByUserIds(IEnumerable<long> userIds)
        {
            var sql = PetaPoco.Sql.Builder;
            sql.Select("Id")
                   .From("spb_BaseCases")
                   .Where("UserId in (@userIds)", new { userIds = userIds });
            return CreateDAO().Fetch<long>(sql);
        }
    }
}
